package top.eggcode.modules.user.tool;

import org.apache.commons.lang3.StringUtils;
import top.eggcode.modules.user.model.PowerView;

import java.util.LinkedList;
import java.util.List;

/**
 * Title: 权限树工具
 * Description: TODO
 * Date: 2021/5/13 22:21
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class PowerTreeTool {
    /**
     * 获取子节点列表
     *
     * @param id       父节点id
     * @param nodeList 全部节点
     * @return 子节点列表
     */
    public static List<PowerView> getLeafNodeList(String id, List<PowerView> nodeList) {
        List<PowerView> rightList = new LinkedList<>();
        nodeList.forEach(node -> {
            if (StringUtils.equals(id, node.getParentId())) {
                rightList.add(node);
            }
        });
        return rightList;
    }

    /**
     * 生成子节点
     */
    public static List<PowerView> generateChildNode(List<PowerView> parentList, List<PowerView> nodeList) {
        parentList.forEach(menu -> {
            List<PowerView> children = getLeafNodeList(menu.getId(), nodeList);
            if (children.size() > 0) {
                // 移除已经确定的节点
                nodeList.removeAll(children);
                // 处理子节点的后代，最后设置给当前节点
                menu.setChildren(generateChildNode(children, nodeList));
            }
        });
        return parentList;

    }

    /**
     * 生成根节点
     */
    public static List<PowerView> generateRootNode(List<PowerView> nodeList) {
        // 一级节点
        List<PowerView> rootList = new LinkedList<>();
        nodeList.forEach(node -> {
            // 为空代表'根节点'
            if (StringUtils.isBlank(node.getParentId())) {
                rootList.add(node);
            }
        });
        // 移除已经确定的节点
        nodeList.removeAll(rootList);
        return generateChildNode(rootList, nodeList);
    }

}
